// Include the libraries:
// LiquidCrystal_I2C.h: https://github.com/johnrickman/LiquidCrystal_I2C
#include <Wire.h> // Library for I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD
#define MAX 32

LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);

int buffer;
int stack[MAX];
int *p;

void setup() {
  // Initiate the LCD:
  lcd.init();
  lcd.backlight();

  // Serial setup
  Serial.begin(9600); // 9
  // while (!Serial);
  Serial.println("\nSimple Calculator");

  // stack setup
  p = stack;
}

void loop () {
  // read func
  char c;
  int op = false;
  int *p2;

  while (Serial.available()) {
    c = Serial.read();
    if ('0' <= c && c <= '9') {
      buffer = buffer * 10 + (c - '0');
    }
    switch (c) {
      case '+': 
        op = true;
        *(p - 2) = *(p - 2) + *(p - 1);
        p--; break;
      case '-':
        op = true;
        *(p - 2) = *(p - 2) - *(p - 1);
        p--; break;
      case '\n': // new line
        if (!op) {
          *p = buffer;
          buffer = 0;
          p++; break;
        }
      // ...
      default: // error
        Serial.println("Error Input. ");
    }
  }

  // TODO: impove this in future 
  lcd.setCursor(0, 0);
  lcd.print(*(p - 2));
  lcd.setCursor(0, 1);
  lcd.print(*(p - 1));

/*
  Serial.print("[");

  for (p2 = stack; p2 < p; p2++) {
    Serial.print(*p2);
    Serial.print(", ");
  }

  Serial.println("]");
*/
}

/*
+ Serial.read read input from computer
+ store read info into buffer

+ if read op
  + calculate
  + update stack
+ if read newline '\n'
  + add new number to stack
+ if read digits
  + add to buffer
+ else
  + raise error

buffer = 11;
{
  8, 
  9,
  ...,
  10, 
  11,
  ? <- p
}

{
  8, 
  9,
  ...,
  21, 
  ? <- p
}
*/